package x.ovo.wechat.bot.core.http.session;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import x.ovo.wechat.bot.core.entity.Contact;
import x.ovo.wechat.bot.core.http.request.BaseRequest;

import java.io.Serializable;
import java.net.HttpCookie;
import java.util.List;
import java.util.Objects;

/**
 * session会话信息
 * <p>
 * 保存用户信息，url、同步密钥等
 *
 * @author ovo, created by 2024/07/06
 */
@Data
@Slf4j
public class Session implements Serializable {

    /** 用户信息 */
    private Contact contact;
    /** 用户名 */
    private String userName;
    /** 昵称 */
    private String nickName;

    /** 网址 */
    private String url;
    /** 文件 URL */
    private String fileUrl;
    /** 同步 URL */
    private String syncUrl;
    /** 设备 ID */
    private String deviceId;
    /** S 键 */
    private String sKey;
    /** WX SID */
    private String wxSid;
    /** WX UIN */
    private String wxUin;

    /** 邀请开始计数 */
    private Integer inviteStartCount;
    /** 基本请求 */
    private BaseRequest baseRequest;
    /** 同步密钥 */
    private SyncKey syncKey;
    /** 同步检查密钥 */
    private SyncKey syncCheckKey;

    private String dataTicket;
    private String passTicket;
    private String authTicket;
    private long lastExitTime = 0;

    public void init(BaseRequest baseRequest, List<HttpCookie> cookies) {
        this.baseRequest = baseRequest;
        this.initializeProperties(baseRequest);
        this.extractTicketsFromCookies(cookies);
        this.setupUrls(cookies);
    }

    private void initializeProperties(BaseRequest baseRequest) {
        this.sKey = baseRequest.getSkey();
        this.wxSid = baseRequest.getSid();
        this.wxUin = baseRequest.getUin();
        this.deviceId = baseRequest.getDeviceID();
        this.passTicket = baseRequest.getPassTicket();
    }

    private void extractTicketsFromCookies(List<HttpCookie> cookies) {
        if (cookies == null || cookies.isEmpty()) {
            return;
        }

        for (HttpCookie cookie : cookies) {
            if (cookie != null) {
                if (cookie.getName().startsWith("webwx_auth_ticket")) {
                    this.authTicket = cookie.getValue();
                }
                if (cookie.getName().startsWith("webwx_data_ticket")) {
                    this.dataTicket = cookie.getValue();
                }
            }
        }
    }

    private void setupUrls(List<HttpCookie> cookies) {
        String domain = determineDomain(cookies);
        this.url = "https://" + domain;
        this.syncUrl = "https://" + domain;
        this.fileUrl = "https://file." + domain;
    }

    private String determineDomain(List<HttpCookie> cookies) {
        if (cookies == null || cookies.isEmpty()) {
            return "wx.qq.com";
        }

        return cookies.stream()
                .map(HttpCookie::getDomain)
                .filter(Objects::nonNull)
                .filter(d -> !d.startsWith("."))
                .findFirst()
                .orElse("wx.qq.com");
    }
}
